package com.dongbo.recorder.screenrecord.ui.fragment;

import android.Manifest;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.dongbo.recorder.screenrecord.ui.activity.LoginActivity;
import com.dongbo.recorder.screenrecord.utils.eventbus.EventMessage;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.interfaces.OnConfirmListener;
import com.tbruyelle.rxpermissions3.RxPermissions;
import com.umeng.analytics.MobclickAgent;
import com.wanglu.photoviewerlibrary.PhotoViewer;
import com.dongbo.recorder.screenrecord.AppLpds;
import com.dongbo.recorder.screenrecord.R;
import com.dongbo.recorder.screenrecord.adapter.PicAdapter;
import com.dongbo.recorder.screenrecord.base.BaseFragment;
import com.dongbo.recorder.screenrecord.bean.ScreenShotBean;
import com.dongbo.recorder.screenrecord.contents.Contents;
import com.dongbo.recorder.screenrecord.utils.FileUtils;
import com.dongbo.recorder.screenrecord.utils.PermissionUtil;
import com.dongbo.recorder.screenrecord.widget.RecycleViewDivider;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import butterknife.BindView;

/**
 * @author GuoZi
 * @date :2020/5/5 20:23
 * @description:
 */
public class PicListFragment extends BaseFragment {
    @BindView(R.id.piclist_rv)
    RecyclerView piclistRv;
    @BindView(R.id.piclist_empty)
    LinearLayout piclistEmpty;
    @BindView(R.id.piclist_srl)
    SwipeRefreshLayout piclistSrl;

    private PicAdapter picAdapter;

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_piclist;
    }

    @Override
    protected void initView(View view, Bundle savedInstanceState) {
        initAdapter();
        getPicList();
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void initListener() {
        piclistSrl.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                getPicList();
            }
        });
    }

    private void initAdapter() {
        piclistRv.setLayoutManager(new LinearLayoutManager(getActivity()));
        piclistRv.addItemDecoration(new RecycleViewDivider(getActivity(), LinearLayout.VERTICAL,
                1, R.color.black));
        if (picAdapter == null) {
            picAdapter = new PicAdapter();
            picAdapter.addChildClickViewIds(R.id.pic_delete, R.id.pic_export);
            picAdapter.setOnItemChildClickListener(new OnItemChildClickListener() {
                @Override
                public void onItemChildClick(@NonNull BaseQuickAdapter adapter, @NonNull View view, int position) {
                    switch (view.getId()) {
                        case R.id.pic_delete:
                            new XPopup.Builder(getActivity()).asConfirm(getResources().getString(R.string.tips),
                                    getResources().getString(R.string.tips_pic_delete),
                                    new OnConfirmListener() {
                                        @Override
                                        public void onConfirm() {
                                            if (FileUtils.deleteFile(((ScreenShotBean) adapter.getItem(position)).getPath())) {
                                                adapter.remove(position);
                                            }
                                        }
                                    })
                                    .show();
                            break;
                        case R.id.pic_export:
                            if (!AppLpds.getInstance().isLogin()) {
                                startActivity(new Intent(getActivity(), LoginActivity.class));
                            }
//                            else if (!AppLpds.getInstance().isVip()) {
//                                startActivity(new Intent(getActivity(), VipActivity.class));
//                            }
                            else {
                                new RxPermissions(PicListFragment.this)
                                        .requestEach(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                                        .subscribe(permission -> {
                                            if (permission.granted) {
                                                String newPath = FileUtils.getRootFile() + picAdapter.getItem(position).getFlieName();
                                                if (FileUtils.getMoveFile(getContext(), picAdapter.getItem(position).getPath(), newPath,true)) {
//                                                    showToast("文件已导出到" + newPath);
                                                    showToast("文件已导出到相册");
                                                } else {
                                                    showToast("文件导出失败");
                                                }
                                            } else if (permission.shouldShowRequestPermissionRationale) {
                                                // Denied permission without ask never again
                                                Log.d("gstory", "不再询问");
                                            } else {
                                                // Denied permission with ask never again
                                                // Need to go to the settings
                                                new XPopup.Builder(getActivity())
                                                        .asConfirm(getResources().getString(R.string.tips),
                                                                getResources().getString(R.string.tips_file_write),
                                                                new OnConfirmListener() {
                                                                    @Override
                                                                    public void onConfirm() {
                                                                        PermissionUtil.gotoPermission(getActivity());
                                                                    }
                                                                })
                                                        .setCancelText(getResources().getString(R.string.btn_sure))
                                                        .setConfirmText(getResources().getString(R.string.btn_gosetting))
                                                        .show();

                                            }
                                        });
                            }
                            break;
                    }
                }
            });
            picAdapter.setOnItemClickListener(new OnItemClickListener() {
                @Override
                public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                    ArrayList<String> list = new ArrayList<>();
                    for (ScreenShotBean screenShotBean : picAdapter.getData()) {
                        list.add(screenShotBean.getPath());
                    }
                    PhotoViewer.INSTANCE.setData(list).setCurrentPage(position)
                            .setImgContainer(piclistRv)
                            .setShowImageViewInterface(new PhotoViewer.ShowImageViewInterface() {
                                @Override
                                public void show(ImageView imageView, String s) {
                                    Glide.with(getActivity()).load(s).into(imageView);
                                }
                            }).start(PicListFragment.this);
                }
            });
        }
        piclistRv.setAdapter(picAdapter);
    }

    //检索截屏文件
    private void getPicList() {
        piclistSrl.setRefreshing(false);
        List<ScreenShotBean> picList = FileUtils.getAllScreenshotFile();
        if (picList.size() != 0) {
            picAdapter.setList(picList);
            piclistRv.setVisibility(View.VISIBLE);
            piclistEmpty.setVisibility(View.GONE);
        } else {
            piclistRv.setVisibility(View.GONE);
            piclistEmpty.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public boolean useEventBus() {
        return true;
    }

    /**
     * 接收到推送的事件
     *
     * @param event 事件
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onPushReceiveEvent(final EventMessage event) {
        //截屏成功
        if (event.getCode() == Contents.EventType.TAG_SHOT_SUCCESS) {
            boolean isRecordSuecss = (boolean) event.getData();
            if (isRecordSuecss) {
                getPicList();
            }
        }
    }

    // Fragment页面onResume函数重载
    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart("PicListFragment"); //统计页面("MainScreen"为页面名称，可自定义)
    }

    // Fragment页面onResume函数重载
    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd("PicListFragment");
    }

}
